//
//  JWAusleseController.m
//  见闻新闻
//
//  Created by brother on 16/3/15.
//  Copyright © 2016年 JoanBoat. All rights reserved.
//

#import "JWAusleseController.h"
#import "JWAuslese.h"
#import "JWTAusleseCell.h"
#import "JWWalfareWebController.h"
#import "JWAusleseLayout.h"
#import "JWImagesCell.h"
#import "JWNewsTool.h"


@interface JWAusleseController ()<UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
//类型
@property (nonatomic ,copy)NSString *appkey;

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
//精选数组
@property (nonatomic ,strong)NSMutableArray *AusleseMutArray;
//美食数组
@property (nonatomic ,strong)NSMutableArray *AusleseMeishiMutArray;
//精选按钮
@property (weak, nonatomic) IBOutlet UIButton *featuredBtn;
//美食按钮
@property (weak, nonatomic) IBOutlet UIButton *gourmetBtn;

@property (nonatomic ,weak)UICollectionView *myCollectionView;
//轮播的数据数组
@property (nonatomic ,strong)NSMutableArray *imageMutArray;
//分页
@property (nonatomic ,weak)UIPageControl *pageControl;
//定时器
@property (nonatomic ,weak)NSTimer *timer;
//自定义view
@property (nonatomic ,weak)UIView *myView;



//@property (nonatomic ,strong)JWAuslese *auslese;


@end

@implementation JWAusleseController
//精选数组赖加载
- (NSMutableArray *)AusleseMutArray {
    if (_AusleseMutArray == nil) {
        _AusleseMutArray = [JWNewsTool selectAllNews];
    }
    return _AusleseMutArray;
}
//轮播数据的数组赖加载
- (NSMutableArray *)imageMutArray {
    if (_imageMutArray == nil) {
        _imageMutArray = [NSMutableArray array];
    }
    return _imageMutArray;
}
//美食数组的赖加载
- (NSMutableArray *)AusleseMeishiMutArray {
    if (_AusleseMeishiMutArray == nil) {
        _AusleseMeishiMutArray = [NSMutableArray array];
    }
    return _AusleseMeishiMutArray;
}
//轮播的cell的Identifier
static NSString *identifier = @"imagesCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView.separatorStyle = UITableViewCellAccessoryNone;
    self.appkey = @"jw10000002";
    self.featuredBtn.selected = YES;
    //一开始被选中的按钮
    if (self.featuredBtn.selected == YES) {
        if ([JWNewsTool ausleseWithQueryAppkey:self.appkey].count > 0) {
            self.AusleseMutArray = [JWNewsTool ausleseWithQueryAppkey:self.appkey];
            [self.myTableView reloadData];
            NSLog(@"11");
        }else {
            [self AusleseAFNData];
            NSLog(@"22");
        }
    }
    //创建出表头
    
    //self.myView = view;
    if (self.imageMutArray.count > 0) {
        [self.myCollectionView reloadData];
        
    }else {
        [self foundWithCollectionView];
        
    }
    
  
}
#pragma mark - 创建CollectionView
- (void)foundWithCollectionView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 200)];
    view.backgroundColor = [UIColor redColor];
    
    self.myTableView.tableHeaderView = view;
    
    JWAusleseLayout *ausleseLayout = [[JWAusleseLayout alloc] init];
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, view.frame.size.height) collectionViewLayout:ausleseLayout];
    [ausleseLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = [UIColor blackColor];
    collectionView.pagingEnabled = YES;
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([JWImagesCell class]) bundle:nil] forCellWithReuseIdentifier:identifier];
    
    [view addSubview:collectionView];
    
    self.myCollectionView = collectionView;
   
    [self imageDataAFN:[NSString stringWithFormat:@"%d",arc4random() %765]];
}



-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //上拉刷新
    [self pullRefreshData];
 
}
#pragma mark - 切换数据
- (IBAction)dataAusleseHandoverBtnClick:(UIButton *)sender {

        if (sender != self.featuredBtn) {
            self.gourmetBtn.selected = YES;
            self.featuredBtn.selected =NO;
            self.appkey = @"jw10000001";
            
            if ([JWNewsTool ausleseWithQueryAppkey:self.appkey].count > 0) {
                self.AusleseMeishiMutArray = [JWNewsTool ausleseWithQueryAppkey:self.appkey];
                [self.myTableView reloadData];
                 NSLog(@"1");
            }else {
                 NSLog(@"2");
                if (self.AusleseMeishiMutArray.count > 0) {
                    [self.myTableView reloadData];
                }else {
                    [self AusleseAFNData];
                }
            }
            
            
        }else {
            self.appkey = @"jw10000002";
            self.gourmetBtn.selected = NO;
            self.featuredBtn.selected = YES;
            if ([JWNewsTool ausleseWithQueryAppkey:self.appkey].count > 0) {
                self.AusleseMeishiMutArray = [JWNewsTool ausleseWithQueryAppkey:self.appkey];
                [self.myTableView reloadData];
                self.myTableView.contentOffset = CGPointZero;
                NSLog(@"3");
            }else {
                 NSLog(@"4");
                if (self.AusleseMutArray.count > 0) {
                    [self.myTableView reloadData];
                    self.myTableView.contentOffset = CGPointZero;
                    
                }else {
                    [self AusleseAFNData];
                }
            }
            
        }
}

#pragma mark - 数据请求
- (void)AusleseAFNData {
    
    NSString *str = @"http://1.zhixinnews.applinzi.com/Home/Featured/queryfeatured";
    NSDictionary *dic = @{@"appkey":self.appkey};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.delegate = self;
    [manager GET:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *dataArray = responseObject[@"data"];
        NSMutableArray *mutArray = [NSMutableArray array];
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            JWAuslese *auslese = [[JWAuslese alloc]initWithAusleseDic:obj];
            
            if ([JWNewsTool ausleseWithQueryId:auslese.jx_id].count > 0) {
                return ;
            }else {
                BOOL sussecc = [JWNewsTool insertNewsWithAuslese:auslese];
                
                if (sussecc) {
                    NSLog(@"成功");
                }else {
                    NSLog(@"失败");
                }
            }

            [mutArray addObject:auslese];
        }];
        
        if (self.featuredBtn.selected == YES) {
            self.AusleseMutArray = mutArray;
            
        }else if (self.gourmetBtn.selected == YES) {
            self.AusleseMeishiMutArray = mutArray;
            
        }else {
            return ;
        }
        
        [hud hide:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1009) {
            return ;
        }
        [hud hide:YES];
    }];
}
#pragma mark - MBProgressHUD代理方法
- (void)hudWasHidden:(MBProgressHUD *)hud {

    if (self.imageMutArray.count > 0) {
        
        [self.myCollectionView reloadData];
        
        [self collectionViewpage];
        
        [self.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:2000 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }
    
    if (self.AusleseMutArray.count > 0) {
        
        [self.myTableView reloadData];
        
        self.myTableView.contentOffset = CGPointZero;
    }
}
#pragma mrak - 数据显示
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.featuredBtn.selected == YES) {
        return self.AusleseMutArray.count;
    }else if (self.gourmetBtn.selected == YES){
        return self.AusleseMeishiMutArray.count;
    }else {
        return 0;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.featuredBtn.selected == YES) {
        JWTAusleseCell *cell = [JWTAusleseCell ausleseWithTabelView:tableView];
        cell.auslese = self.AusleseMutArray[indexPath.row];
        return cell;
    }else if (self.gourmetBtn.selected == YES){
        JWTAusleseCell *cell = [JWTAusleseCell ausleseWithTabelView:tableView];
        cell.auslese = self.AusleseMeishiMutArray[indexPath.row];
        return cell;
    }else {
        return 0;
    }
    
}
#pragma mark - tabView的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 260;
}

#pragma mark - 点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.featuredBtn.selected == YES) {
        [self massHtmlField:self.AusleseMutArray[indexPath.row]];
        
    }else if (self.gourmetBtn.selected == YES){
        [self massHtmlField:self.AusleseMeishiMutArray[indexPath.row]];
    }else {
        return;
    }
    
}
//传网页字段
- (void)massHtmlField:(JWAuslese *)auslese {
    JWWalfareWebController *webController = [[JWWalfareWebController alloc]initWithNibName:@"JWWalfareWebController" bundle:nil];
    webController.htmlFieldBlock = ^JWAuslese *{
        return auslese;
    };
    [self.navigationController pushViewController:webController animated:YES];
}

#pragma mark - 上拉刷新
- (void)pullRefreshData {
        self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (self.featuredBtn.selected == YES) {
                if (self.AusleseMutArray.count > 0) {
                    [self dataMax:self.AusleseMutArray];
                }
                [self.myTableView.mj_footer endRefreshing];
            }else if (self.gourmetBtn.selected == YES){
                if (self.AusleseMeishiMutArray.count > 0) {
                    [self dataMax:self.AusleseMeishiMutArray];
                }
                [self.myTableView.mj_footer endRefreshing];
            }else {
                return ;
            }
            
        }];
}

- (void)dataMax:(NSMutableArray *)mutArray{
    JWAuslese *auslese = [mutArray lastObject];
    [self shanglaRefreshAFFFFFF:auslese.jx_id dataMutArray:mutArray];
}

- (void)shanglaRefreshAFFFFFF:(NSString *)max_id dataMutArray:(NSMutableArray *)dataMutArray {
   
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"正在加载";
        NSString *str = @"http://1.zhixinnews.applinzi.com/Home/Featured/showFeaturedPage";
        NSDictionary *dic = @{@"max_id":max_id};
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
        [manager GET:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *dataArray = responseObject[@"data"];
            
            NSMutableArray *mutArray = [NSMutableArray array];
            
           [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
               JWAuslese *auslese = [[JWAuslese alloc]initWithAusleseDic:obj];
               [mutArray addObject:auslese];
           }];
            
           NSMutableArray *tempArray = [NSMutableArray array];
            if (mutArray.count > 0) {
                
                [mutArray removeObjectAtIndex:0];
                
            }
            [tempArray addObjectsFromArray:dataMutArray];
            [tempArray addObjectsFromArray:mutArray];
            
            if (self.featuredBtn.selected == YES) {
                
                self.AusleseMutArray = tempArray;
            }else if (self.gourmetBtn.selected == YES){
                
                self.AusleseMeishiMutArray = tempArray;
            }else {
                return ;
            }
            
            
            [hud hide:YES];
            [self.myTableView reloadData];


        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error.code == -1099) {
                return ;
            }else {
                [hud hide:YES];
            }
        }];
    
}
//http://1.zhixinnews.applinzi.com/Home/Featured/queryfeaturedRandomId

#pragma mark - image的数据
- (void)imageDataAFN:(NSString *)random_id {
    NSString *str = @"http://1.zhixinnews.applinzi.com/Home/Featured/queryfeaturedRandomId";
    NSDictionary *dic = @{@"random_id":random_id};
    MBProgressHUD *bbb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    bbb.labelText = @"";
    bbb.delegate = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        NSMutableArray *mutArray = [NSMutableArray array];
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            JWAuslese *auslese = [[JWAuslese alloc]initWithAusleseDic:obj];
            [mutArray addObject:auslese];
        }];
        self.imageMutArray = mutArray;
        
       
        [self.myCollectionView reloadData];
        [bbb hide:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1009) {
            return ;
        }else {
            [bbb hide:YES];
        }
    }];
}

#pragma mark - 设置UIPageControl

- (void)collectionViewpage {
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    
    CGPoint tempPoint = self.myCollectionView.center;
    
    tempPoint.y += 90;
    
    pageControl.center = tempPoint;
    
    pageControl.pageIndicatorTintColor = [UIColor blueColor];
    
    pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    
    pageControl.numberOfPages = self.imageMutArray.count;
    
    self.pageControl = pageControl;
    
    [self.myTableView.tableHeaderView addSubview:pageControl];
    
    [self addCurrentTimer];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat contentOffSetX = scrollView.contentOffset.x ;
    CGFloat myCollectionView = scrollView.frame.size.width;
    //意思是可以在图片滑动到一半是 pageControl 就会跳到下一张图片上
    
    int a = (int)((contentOffSetX + myCollectionView * 0.5) / myCollectionView) % self.imageMutArray.count;
    self.pageControl.currentPage = a;
    // NSLog(@"asdasdasdas");
}


#pragma mark - 添加定时器

- (void)addCurrentTimer {
    [self removeCurrentTimer];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(cycleImage) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

#pragma mark - 删除定时器

- (void)removeCurrentTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark - 定时器自动移动的方法

- (void)cycleImage {
    //1 获取当前正在展示的位置
    NSIndexPath *currentInteger = [[self.myCollectionView indexPathsForVisibleItems]lastObject];
    //2 马上显示回中间的那组数据
    NSIndexPath *currentIndexPathRest = [NSIndexPath indexPathForItem:currentInteger.item inSection:0];
    //3 计算出下一个需要展示的位置
    NSInteger nextItem = currentIndexPathRest.item + 1;
    NSInteger nextSection = currentIndexPathRest.section;
    if (nextItem == self.imageMutArray.count) {
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    
    
    //4 通过动画滚动到下一位置
    [self.myCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    
}

#pragma mark - 在控制scrollView时要删除定时器
// 移动快要停止是调用的方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.myCollectionView == scrollView) {
        [self removeCurrentTimer];
    }
}
#pragma mark - 在不控制scrollView时要添加定时器
// 在不控制UIScrollView时添加定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.myCollectionView == scrollView) {
        [self addCurrentTimer];
    }
}


#pragma mark -collectionView的轮播数据
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageMutArray.count * 2000;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JWImagesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.auslese = self.imageMutArray[indexPath.item % self.imageMutArray.count];;
    return cell;
}
#pragma mark - collectionViewCell的宽高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.frame.size.width, self.myTableView.tableHeaderView.frame.size.height);
}
#pragma mark - collectionView的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self massHtmlField:self.imageMutArray[indexPath.item % self.imageMutArray.count]];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
